﻿@*@model IList<FaultDiagnosisSystem.Models.DataModels.v_TenMeanData>*@
@{
    ViewBag.Title = "十分钟数据对比曲线";
}
<link href="~/Content/RealTimeFault/TenMeanCompare.css" rel="stylesheet" />
<link href="~/Content/bootstrap-datepicker.min.css" rel="stylesheet" />

<section class="content">
    <!--内容标题-->
    <div class="content-title row">
        <div class="col-md-4">
            <h3 class="title-brand">十分钟数据对比曲线</h3>
        </div>
        <div class="col-md-8">
            @using (Html.BeginForm("TenMeanCompare", "RealTimeFault", FormMethod.Get, new { id = "componentForm", @class = "form-inline title-form" }))
            {
                <div class="form-group">
                    <label class="control-label" for="">部件</label> <span class="glyphicon glyphicon-search"></span>
                    @Html.DropDownList("ComponentSelect", (IEnumerable<SelectListItem>)ViewBag.ComponentSelectList, new { @class = "form-control", form = "" })
                </div>
                <div class="form-group">
                    <label class="control-label" for="">传感器</label> <span class="glyphicon glyphicon-search"></span>
                    <select class="form-control" id="SensorSelect"></select>
                </div>
                <div class="form-group">
                    <label class="control-label" for="">日期</label> <span class="glyphicon glyphicon-search"></span>
                    @*@Html.DropDownList("DateSelect", (IEnumerable<SelectListItem>)ViewBag.DateSelectList, new { @class = "form-control" })*@
                    <input class="form-control" type="text" id="DatePicker" />
                    <button id="btnOK" class="btn btn-default form-control" type="button">确定</button>
                </div>
                <div class="form-group">
                    <button type="button" class="btn btn-default form-control" id="btnLastDay">最近一天数据</button>
                </div>
            }
        </div>
    </div>
    <div class="content-charts row">
        @for (int i = 0; i < 28; i++)
        {
            <div class="col-md-4">
                <div class="panel panel-chart">
                    <div class="panel-heading">@(i + 1)号风机</div>
                    <div class="panel-body">
                        <div class="chart" id='chart_@i'></div>
                    </div>
                </div>
            </div>
        }
    </div>
</section>

@section Scripts{
    <script src="~/Scripts/echarts.min.js"></script>
    <script src="~/Scripts/bootstrap-datepicker.min.js"></script>
    <script src="~/Scripts/bootstrap-datepicker.zh-CN.min.js"></script>

    <!--左侧导航显示-->
    <script>
        $(function () {
            //展开当前左侧栏父节点
            $("#RealTime").addClass("in");
            $("#RealTime>li:nth-child(2)>a").addClass("sidebar-active");
        });
    </script>

    <!--initial-->
    <script>
        //初始参数
        var _firstSensorId = "";
        var _firstComponentId = "";
        var _firstDate = "";

        $(function () {
            setFirstValue();

            buildComponentJson();
            bindSensorSelectOption();   //绑定传感器下拉列表项
            bindEvents();   //绑定下拉列表事件
            initialDatePicker();

            initialCharts();   //初始化图表
            readSensorData();  //读取数据
        })

        //设置初始参数
        var setFirstValue = function () {
            _firstSensorId = '@ViewBag.SensorId';
            _firstComponentId = '@ViewBag.ComponentId';
            _firstDate = '@ViewBag.Date';
        }
    </script>

    <!-- 操作日历控件 -->
    <script>
        function initialDatePicker() {
            $("#DatePicker").val('@ViewBag.LastDay');
            $('#DatePicker').datepicker({
                format: "yyyy-mm-dd",
                language: "zh-cn",
                autoclose: true
            });
        }
    </script>

    <!-- 操作下拉列表 -->
    <script>
        /* ViewBag.SensorDict转component对象 */
        var component = {};   //部件对象，包含传感器
        var buildComponentJson = function () {
            @foreach (var pair in ViewBag.ComponentDict
            as Dictionary<int, FaultDiagnosisSystem.Models.DataModels.Component>)
            {
                <text>component['</text>@pair.Key<text>'] = [];</text>
                foreach (var sensor in pair.Value.Sensor)
                {
                    <text>component['</text>@pair.Key<text>']
                        .push({ 'sensorId': '</text>@sensor.SensorId<text>', 'sensorZH': '</text>@sensor.SensorZH<text>' });</text>
                }
            }
        }

        /* 绑定事件 */
        var bindEvents = function () {
            //$("#DateSelect").change(function () {
            //    readSensorData();  //读取数据
            //})
            $("#btnOK").click(function () {
                readSensorData();  //读取数据
            });
            $("#btnLastDay").click(function () {
                readSensorDataOfLastDay();  //读取数据
            });
            $("#ComponentSelect").change(function () {
                bindSensorSelectOption($("#ComponentSelect").val());
                loadSensorCharts();//构建数据并渲染
            })
            $("#SensorSelect").change(function () {
                loadSensorCharts();//构建数据并渲染
            })
        }

        /* 绑定传感器下拉列表项 */
        var bindSensorSelectOption = function () {
            $("#SensorSelect option").remove();
            var componentId = $("#ComponentSelect").val();
            component[componentId].forEach(function (sensor) {
                $("#SensorSelect").append("<option value='" + sensor['sensorId'] + "'>" + sensor['sensorZH'] + "</option>");
            })
        }




    </script>

    <!-- 操作图表 -->
    <script>
        //图表页全局变量
        var _sensorData;
        var _options = [];
        var _eCharts = [];
        var _option = {
            title: {
                text: ""
            },
            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                    var result = "";
                    if (params[0].data != null) {
                        result = params[0].data[0];
                        params.forEach(function (series) {
                            result += '<br />';
                            result += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + series.color + '"></span>'
                            result += series.seriesName + ' : ';
                            result += series.data[1] == null ? null : (series.data[1].toFixed(2) + ' ℃');
                        })
                    }
                    return result;
                }
            },
            legend: {
                top: 30,
                right: 30,
                data: ['风机数据', '风场平均']
            },
            xAxis: {
                type: 'time'
            },
            yAxis: {},
            series:
            [{
                name: '风机数据',
                type: 'line',
                showSymbol: false,
                data: []
            },
            {
                name: '风场平均',
                type: 'line',
                showSymbol: false,
                areaStyle: { //区域填充样式
                    normal: {
                        //线性渐变，前4个参数分别是x0,y0,x2,y2(范围0~1);相当于图形包围盒中的百分比。如果最后一个参数是‘true’，则该四个值是绝对像素位置。
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: 'rgba(110, 125, 136, 0.3)'
                        }, {
                            offset: 0.8,
                            color: 'rgba(110, 125, 136, 0)'
                        }], false),

                        shadowColor: 'rgba(0, 0, 0, 0.3)', //阴影颜色
                        shadowBlur: 10 //shadowBlur设图形阴影的模糊大小。配合shadowColor,shadowOffsetX/Y, 设置图形的阴影效果。
                    }
                },
                data: []
            }]
        };

        //初始化图表
        var initialCharts = function () {
            for (var i = 0; i < 28; i++) {
                _eCharts[i] = echarts.init(document.getElementById('chart_' + i));
            }
        }

        //打开页面，及改变日期后，重新给_sensorData赋值
        function readSensorData() {

            //显示加载中
            _eCharts.forEach(function (e) {
                e.showLoading();
            })

            var date;

            //如果有初始参数
            if (_firstDate != "") {
                date = _firstDate;
                $("#DatePicker").val(_firstDate);
                _firstDate = "";
            }
            else {
                date = $("#DatePicker").val();
            }

            //读取数据
            var patt = /\b[12][0-9][0-9][0-9]-[012]?[0-9]-[0123]?[0-9]\b/;

            if (date != null && patt.test(date)) {
                var data = { "day": date };
                $.getJSON('@Url.Action("GetSensorData", "RealTimeFault")', data, function (result) {
                    if (result != null && result.count != 0) {
                        _sensorData = result;
                        loadSensorCharts();
                    }
                })
            }
        }

        //打开页面，及改变日期后，重新给_sensorData赋值
        function readSensorDataOfLastDay() {

            //显示加载中
            _eCharts.forEach(function (e) {
                e.showLoading();
            })

            //读取数据
                $.getJSON('@Url.Action("GetSensorDataOfLastDay", "RealTimeFault")', function (result) {
                    if (result != null && result.count != 0) {
                        _sensorData = result;
                        loadSensorCharts();
                    }
                })
        }

        //构建图表数据，并渲染
        var loadSensorCharts = function () {
            buildChartsOption();

            _eCharts.forEach(function (e) {
                e.hideLoading();
            })

            setChartsOption();
        }

        //构建数据
        function buildChartsOption() {
            for (var i = 0; i < 28; i++) {
                _options[i] = {};
                $.extend(true, _options[i], _option);
            }

            //如果有初始参数
            if (_firstSensorId != "") {
                sensorId = _firstSensorId;

                $("#ComponentSelect").val(_firstComponentId);
                bindSensorSelectOption(_firstComponentId);
                $("#SensorSelect").val(_firstSensorId);

                _firstComponentId = "";
                _firstSensorId = "";
            }
            else {
                sensorId = $("#SensorSelect").val();
            }

            if (sensorId != null) {
                $.each(_sensorData, function (turbineId, value) {   //key为字符串
                    var index = parseInt(turbineId) - 1;
                    switch (sensorId) {
                        case '1':
                            _options[index]["title"]["text"] = turbineId + '号风机 齿轮箱温度';
                            value.forEach(function (item) {
                                _options[index]["series"][0]["data"].push([convertToDate(item["TimeStamp"]).format("yyyy-MM-dd hh:mm:ss"), item["GBoxDegC_Mean"]]);
                                _options[index]["series"][1]["data"].push([convertToDate(item["TimeStamp"]).format("yyyy-MM-dd hh:mm:ss"), item["GBoxDegC_FarmMean"]]);
                            })
                            break;
                        case '2':
                            _options[index]["title"]["text"] = turbineId + '号风机 发电机温度';
                            value.forEach(function (item) {
                                _options[index]["series"][0]["data"].push([convertToDate(item["TimeStamp"]).format("yyyy-MM-dd hh:mm:ss"), item["GenDegC_Mean"]]);
                                _options[index]["series"][1]["data"].push([convertToDate(item["TimeStamp"]).format("yyyy-MM-dd hh:mm:ss"), item["GenDegC_FarmMean"]]);
                            })
                            break;
                        default:
                    }
                })
            }

        }

        //渲染
        function setChartsOption() {
            for (var i = 0; i < 28; i++) {
                _eCharts[i].setOption(_options[i]);
            }
        }
    </script>

}

